local skynet = require "skynet"
local filelog = require "filelog"
local timer = require "timer"

require "hbslenum"

local server = nil
local tablecmd = {}

function tablecmd.init(service)
	if server == nil then server = service end
end

function tablecmd.start(conf, node_id)
	if conf == nil or node_id == nil then
		filelog.sys_error(filename .. "conf == nil or node_id == nil")
		return false
	end
	local tablelogic = server:get_logicbyname("tablelogic")
	tablelogic.init_data(server.table_data, conf, node_id)
	skynet.pcall(skynet.retpack, true)
end

function tablecmd.delete(delreason)
	local table_data = server.table_data
	local roomtablelogic = server:get_logicbyname("tablelogic")
	local rids = roomtablelogic.getallrids(table_data)
	--踢出座位上的玩家
	roomtablelogic.standupallplayer()
	skynet.send(".router", "lua", "delete_table", table_data.conf.table_index, rids)
	--延迟释放桌子
	skynet.sleep(10)
	server:exit_service()
end

function tablecmd.update_stop_server(flag)
	local table_data = server.table_data
	local tablelogic = server:get_logicbyname("tablelogic")
	table_data.table_end_flag = flag
	if table_data.state == HBSLTableState.TABLE_STATE_WAIT_PLAYER_BURY_LANDMINE then
		tablelogic.resetdata()
        table_data.state = HBSLTableState.TABLE_STATE_GAME_START_OVER
        if table_data.delete_table_timer_id > 0 then
            timer.cleartimer(table_data.delete_table_timer_id)
            table_data.delete_table_timer_id = -1
        end
        if table_data.delete_table_timer_id == -1 then
            local noticemsg = {
                table_index = table_data.conf.table_index,
                reason = "tableend",
            }
            table_data.delete_table_timer_id = timer.settimer(1*100, "delete_table", noticemsg)
        end
    end
	---return true
	skynet.pcall(skynet.retpack, true)
end

function tablecmd.rid_change_diamond(rid, beginvalue, value, endvalue)
	local table_data = server.table_data
	local tablelogic = server:get_logicbyname("tablelogic")
	--filelog.sys_error("--------------tablecmd.rid_change_diamond---------", rid, beginvalue, value, endvalue)
	local seat = tablelogic.get_seat_by_rid(table_data, rid)
	if seat then
		--filelog.sys_error("---------seat.diamond--------", seat.diamond, endvalue)
		seat.diamond = endvalue
		--[[
			message money_change_item {
				optional int32 rid = 1;
				optional int32 money_type = 2; // 金钱类型:1 得分 2 钻石
				optional int32 change_value = 3; //变化值
				optional int32 final_value = 4; // 最终结果值
			}
			//牌桌内通知金钱改变
			message moneychangeN {
				repeated money_change_item money_change_list = 1;  //diamond变化列表
			}
		--]]
		local moneychangeNtc = {
			money_change_list = {}
		}
		local moneychangeitem = {
			rid = seat.rid,
			money_type = 2,
			change_value = value,
			final_value = endvalue,
		}
		table.insert(moneychangeNtc.money_change_list, moneychangeitem)
		server:send_notice_to_players({seat.rid}, "moneychangeN", moneychangeNtc, nil, nil)
	end
end


return tablecmd